package data

import (
	"time"

	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"

	"gitee.com/architect-training/substitute-driver/customer-srv/internal/biz"
	"gitee.com/architect-training/substitute-driver/customer-srv/internal/conf"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/google/wire"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewGreeterRepo, NewCustomerData)

// Data .
type Data struct {
	rdb *redis.Client
	mdb *gorm.DB
}

// NewData .
func NewData(c *conf.Data, logger log.Logger) (*Data, func(), error) {
	data := &Data{}

	// 初始化 redis cli
	rdb := redis.NewClient(&redis.Options{
		Addr:        c.Redis.Addr,
		Password:    c.Redis.Password,
		DB:          int(c.Redis.Db),
		DialTimeout: time.Duration(c.Redis.DialTimeout),
	})
	if rdb == nil {
		log.Info("connection to redis failed")
	} else {
		log.Info("connection to redis succeeded")
		data.rdb = rdb
	}

	// 初始化 mysql cli
	dsn := c.Database.Source
	mdb, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("connection to mysql failed: ", err)
	} else {
		log.Info("connection to mysql succeeded")
		data.mdb = mdb
	}

	// 开发阶段，自动迁移表。发布阶段，表结构稳定，不需要 migrate。
	migrateTable(mdb)

	cleanup := func() {
		// 清理 Redis 连接
		_ = data.rdb.Close()
		log.NewHelper(logger).Info("closing the data resources")
	}
	return data, cleanup, nil
}

func migrateTable(db *gorm.DB) {
	if err := db.AutoMigrate(&biz.Customer{}); err != nil {
		log.Info("customer table migration error, err:", err)
	}
}
